package com.hmdp.lock;
import cn.hutool.core.util.BooleanUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import cn.hutool.core.lang.UUID;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Lock implements ILock{
    private String name;
    private StringRedisTemplate stringRedisTemplate;
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";
    //提前定义好脚本,并初始化
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
    /**
     * 尝试获取锁
     * @param timeoutSec 锁的过期时间
     * @return 是否获取成功
     */
    @Override
    public boolean tryLock( long timeoutSec) {
        //获取线程Id
        String threadId = ID_PREFIX+Thread.currentThread().getId() ;
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId,timeoutSec, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);//防止拆箱之后抛出空指针异常
    }
    /**
     * 释放锁
     */
    @Override
    public void unLock(String key) {
        /*//方法一：判断后释放锁，不具有原子性
        String threadId = ID_PREFIX+Thread.currentThread().getId();
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        //判断锁是否属于当前线程，如果是，则释放锁
        //Redis使用lua脚本编程，保证判断锁跟释放锁的原子性
        if (threadId.equals(id)) {
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }*/

        //方法二：原子性操作，使用lua脚本
        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX+Thread.currentThread().getId());

    }
}
